import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:get/get.dart';
import 'package:happy_study/core/model/student_model.dart';
import 'package:happy_study/core/model/user_model.dart';
import 'package:happy_study/core/shared_preference/shared_preference_util.dart';
import 'package:happy_study/core/shared_preference/sp.dart';
import 'package:happy_study/ui/main/main_logic.dart';
import 'package:happy_study/ui/shared/app_theme.dart';
import 'package:happy_study/ui/shared/compute.dart';

import '../main/main_view.dart';
import 'login_state.dart';

class LoginLogic extends GetxController {
  final LoginState state = LoginState();

  @override
  void onReady() {
    initUsers();
    super.onReady();
  }

  @override
  void onClose() {
    state.userNameController.dispose();
    state.passwordController.dispose();
    super.onClose();
  }

  ///初始化用户信息
  initUsers() {
    ///获取所有用户信息
    state.userDao.getAllUsers().then((value) {
      if (value.isNotEmpty) {
        state.isNeedCreateUser = false;

        ///查询上次登录信息
        String? userId = SharedPreferenceUtil.getString(SP.userId);
        state.userId = userId ?? "";
        if (userId != null) {
          state.userDao.getUserByUserId(userId).then((value) {
            state.user = value!;
            update();
          });
        }
      } else {
        state.isNeedCreateUser = true;
        showLoginDialog();
      }
    });
  }

  ///点击登录按钮
  clickLoginButton() {
    if (state.userId.isNotEmpty) {
      MainLogic mainLogic = Get.find<MainLogic>();
      mainLogic.fetchStudents();
      Get.toNamed(Mainview.routeName);
    } else {
      showLoginDialog();
    }
  }

  ///注册、登录弹框
  showLoginDialog() {
    SmartDialog.show(
      builder: (ctx) {
        return Container(
          width: 200.w,
          decoration: BoxDecoration(
              color: HYAppTheme.norWhite01Color,
              borderRadius: BorderRadius.all(Radius.circular(20.r))),
          padding: EdgeInsets.symmetric(vertical: 20.r, horizontal: 15.r),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              TextField(
                controller: state.userNameController,
                onChanged: (value) {
                  state.userName = value;
                },
                decoration: const InputDecoration(
                  prefixIcon: Icon(Icons.account_box),
                ),
              ),
              TextField(
                obscureText: true,
                controller: state.passwordController,
                onChanged: (value) {
                  state.password = value;
                },
                decoration: const InputDecoration(
                  prefixIcon: Icon(Icons.password),
                ),
              ),
              InkWell(
                onTap: () async {
                  ///注册一个新的用户
                  if (state.userNameController.text.isNotEmpty &&
                      state.passwordController.text.isNotEmpty) {
                    UserModel user = UserModel(
                      userId: getRandomNum(),
                      userName: state.userName,
                      userLevel: 0,
                      password: state.password,
                      userExperience: 0,
                    );
                    state.userDao.insert(user).then((value) {
                      SharedPreferenceUtil.setString(SP.userId, user.userId);
                      state.userId = user.userId;
                      state.user = user;
                      state.isNeedCreateUser = false;
                      SmartDialog.dismiss();
                      update();
                    });

                    ///初始化学生
                    for (int i = 0; i < 32; i++) {
                      StudentModel student = StudentModel(
                        studentId: getRandomNum(),
                        studentName: getRandomStudentName(),
                        studentLevel: 0,
                        studentExperience: 0,
                      );
                      await state.studentDao.insert(student);
                    }
                  } else {
                    SmartDialog.showToast("请将信息填写完整");
                  }
                },
                child: Container(
                  decoration: BoxDecoration(
                      color: HYAppTheme.norTextColors.withOpacity(.5)),
                  alignment: Alignment.center,
                  padding: EdgeInsets.symmetric(vertical: 10.r),
                  width: 1.sw,
                  child: Text("注册"),
                ),
              )
            ],
          ),
        );
      },
    );
  }
}
